import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';

import buffer from '@ohos.buffer';


//使用访问云函数的话，要导入下面三个包
import agconnect from '@hw-agconnect/api-ohos';
import "@hw-agconnect/core-ohos";
import "@hw-agconnect/function-ohos";


//  访问云数据库要导入下面两个包
import { initialize } from '@hw-agconnect/hmcore';

//import jsonString from "../../resources/rawfile/agconnect-services.json"   // 因为该文件类型是.ts  后缀，所以在导入json文件时会报这个红线提示，但不影响功能，后续华为应该会修复该问题

export default class EntryAbility extends UIAbility {
  onCreate() {

    let AtManager = abilityAccessCtrl.createAtManager();
    AtManager.requestPermissionsFromUser(this.context, ['ohos.permission.READ_MEDIA', 'ohos.permission.MEDIA_LOCATION']).then((data) => {
      hilog.info(0x0000, 'testTag', '%{public}s', 'request permissions from user success' + data);
    }).catch((err) => {
      hilog.error(0x0000, 'testTag', 'Failed to request permissions from user. Cause: %{public}s', JSON.stringify(err) ?? '');
    });
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');


    //将端侧与云端（云函数、认证服务,云存储）连接在一起，使用typeScript版本调用云函数必须要填写这行
    agconnect.instance().init(this.context.getApplicationContext());

    //初始化 云数据库SDK，如果下面的onWindowStageCreate 生命周期中没有初始化这个sdk，则需要再这里初始化
    //initialize(this.context,jsonString);

  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  async onWindowStageCreate(windowStage: Window.WindowStage) {
    const context = this.context
    const value = await context.resourceManager.getRawFileContent("agconnect-services.json");
    let json: string = buffer.from(value).toString("utf8");
    initialize(this.context, JSON.parse(json));

    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });

  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
